package tornadoj.data;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import tornadoj.web.TornadoJConfiguration;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.util.Properties;

public class Jdbc {
    private final static Logger Log = LoggerFactory.getLogger(Jdbc.class);
    private static ComboPooledDataSource c3p0 = new ComboPooledDataSource();
    private static boolean inited = false;

    private static void initPool() {
        if (!inited) {
            TornadoJConfiguration.loadProperties();
            Properties prop = TornadoJConfiguration.Items;
            c3p0.setJdbcUrl(prop.getProperty("c3p0.jdbc_url"));
            c3p0.setUser(prop.getProperty("c3p0.user"));
            c3p0.setPassword(prop.getProperty("c3p0.password"));
            c3p0.setInitialPoolSize(NumberUtils.toInt(prop.getProperty("c3p0.initial_pool_size")));
            c3p0.setMaxIdleTime(NumberUtils.toInt(prop.getProperty("c3p0.max_idle_time")));
            c3p0.setMaxPoolSize(NumberUtils.toInt(prop.getProperty("c3p0.max_pool_size")));
            c3p0.setMinPoolSize(NumberUtils.toInt(prop.getProperty("c3p0.min_pool_size")));
            try {
                c3p0.setDriverClass(prop.getProperty("c3p0.driver_class"));
            } catch (PropertyVetoException e) {
                Log.error(e.getLocalizedMessage(), e);
            }
            inited = true;
        }
    }

    public static DataSource getDataSource() {
        initPool();
        return c3p0;
    }

    /**
     * Jdbc Transaction Manager
     *
     * @return
     */
    public static TransactionTemplate transaction() {
        return new TransactionTemplate(new DataSourceTransactionManager(getDataSource()));
    }

    /**
     * Spring JdbcTemplate, example: where filed = ?
     *
     * @return
     */
    public static JdbcTemplate base() {
        return new JdbcTemplate(getDataSource());
    }

    /**
     * Spring NamedParameterJdbcTemplate, example: where filed = :alias
     *
     * @return
     */
    public static NamedParameterJdbcTemplate named() {
        return new NamedParameterJdbcTemplate(getDataSource());
    }
}
